import { ComponentFactory, ComponentRef, InjectionToken, Injector, ReflectiveInjector } from '@angular/core';
import { Observable, Subject } from 'rxjs';

export const DIALOG_REF_DATA = new InjectionToken("xixi-ui-dialog-ref-data");

export class DialogRef<T> {
    private afterClose$: Subject<any>;
    private myRef: ComponentRef<any>;
    
    constructor(
        private factory:ComponentFactory<T>,
        private config: any
    ) {      
        this.afterClose$ = new Subject<any>();
        this.myRef = this.factory.create(
            Injector.create({providers: [
                { provide: DIALOG_REF_DATA, useValue:config },
                { provide: DialogRef, useValue: this }
            ]})
        );
    }
    afterClose(): Observable<any> {
        return this.afterClose$.asObservable();        
    }
    close(data?:any) {
        this.afterClose$.next(data);
        this.afterClose$.complete();
        this.myRef.destroy();
    }
    componentRef() {
        return this.myRef;         
    }

}